/**
 * 
 */
package org.statewalker.parser.wiki.tokenizer.inline;

import org.statewalker.parser.wiki.tokenizer.base.StreamToken;
import org.statewalker.tokenizer.base.AbstractTokenizer;
import org.statewalker.tokenizer.base.ITokenFactory;
import org.statewalker.tokenizer.stream.ICharStream;
import org.statewalker.tokenizer.stream.ICharStream.IMarker;

public class EscapedTokenizer extends AbstractTokenizer<StreamToken> {

    private char fEscapeChar;

    public EscapedTokenizer(ITokenFactory<StreamToken> factory) {
        this(factory, '\\');
    }

    public EscapedTokenizer(ITokenFactory<StreamToken> factory, char esc) {
        super(factory);
        fEscapeChar = esc;
    }

    /**
     * @see org.statewalker.tokenizer.base.ITokenizer#read(org.statewalker.tokenizer.stream.ICharStream)
     */
    public StreamToken read(ICharStream stream) {
        char ch = stream.getChar();
        if (ch != fEscapeChar)
            return null;
        StreamToken result = null;
        IMarker marker = stream.markPosition();
        try {
            if (!stream.incPos())
                return result;
            if (!stream.incPos())
                return result;
            result = newToken(stream, marker);
            return result;
        } finally {
            marker.close(result == null);
        }
    }
}